package com.github.hxl.upload.demo.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletResponse;

/**
 * 文件下载
 * 
 * @author: shizi
 */
public class FileDownLoadUtil {

	/**
	 * 文件下载方法
	 * 
	 * @param response
	 * @param path 下载文件地址
	 * @return 如果成功返回success 失败返回fail
	 * @throws IOException
	 */
	public static String download(HttpServletResponse response, String path) throws Exception {
		File file = new File(path);
		String filename = file.getName();
		InputStream is = null;
		try {
			is = new BufferedInputStream(new FileInputStream(path));
			byte[] buffer = new byte[is.available()];
			is.read(buffer);
			// 清空response
			response.reset();
			// 设置response的Header
			response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
			response.addHeader("Content-Length", "" + file.length());
			OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
			response.setContentType("application/octet-stream");
			toClient.write(buffer);
			toClient.flush();
			toClient.close();
		} finally {
			if (null != is) {
				try {
					is.close();
				} catch (IOException e) {
				}
			}
		}
		return "success";
	}
}
